package org.gdpu.action;

import com.opensymphony.xwork2.ModelDriven;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.gdpu.model.*;
import org.gdpu.service.ExaminerService;
import org.gdpu.service.PersonService;
import org.gdpu.service.SubjectService;
import org.gdpu.service.TestService;
import org.gdpu.util.ChangeTime;
import org.gdpu.util.ExcelUtil;
import org.gdpu.vo.FileVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Component("file")
@Scope("prototype")
public class FileAction extends MyActionSupport implements ModelDriven<FileVO> {

    @Qualifier("excelUtil")
    @Autowired
    private ExcelUtil excelUtil;

    private final static Logger logger = LogManager.getLogger(FileAction.class);
    private final FileVO fileVO = new FileVO();
    private ExaminerService examinerService;
    private SubjectService subjectService;
    private TestService testService;
    private PersonService personService;
    private List<Examiner> es = new ArrayList<Examiner>();
    private List<Person> ps = new ArrayList<Person>();
    private List<Test> ts = new ArrayList<Test>();
    private List<Object> obj = new ArrayList<Object>();
    private int count = 0;
    private static String SAVE_PATH_DIR = "D:/CRM/_file/_excel/_examiner/";

    public String createExcelByExaminer() {

        // 得到备份文件的目录的真实路径
        File dir = new File(SAVE_PATH_DIR);
        // 如果该目录不存在，就创建
        if (!dir.exists()) {
            dir.mkdirs();
        }
        es = examinerService.allExaminer();
        if (es.size() <= 0) {
            fileVO.setResultMessage("考生信息为空！");
            return ERROR;
        }
        String date = ChangeTime.formatDate(ChangeTime.getCurrentDate());
        //使用于07以上的版本，03以下的可以修改参数
        excelUtil.exportExcelByPath(SAVE_PATH_DIR + date + ".xlsx",
                es, Examiner.class, true, date + " 考生信息 ");
        logger.trace("成功备份考生信息文件！文件名为" + date);
        fileVO.setResultMessage("成功备份考生信息文件！文件名为" + date);
        return SUCCESS;
    }

    public String recoverExcelByExaminer() {
        try {
            ExcelUtil.owner =  fileVO.getOwner();
            obj = excelUtil.readExcelByPath(fileVO.getFile(),Person.class, 4, 0);
            for (Object anObj : obj) {
                ps.add((Person) anObj);
            }
            for (Person person : ps) {
                Person temp = new Person();
                Examiner examiner = new Examiner();
                if((temp = personService.findPersonByAccout(person.getAccout())) == null){
                    person.setPassword(person.getAccout());
                    person.setGroups(new Groups("学生"));
                    personService.save(person);
                    temp = personService.findPersonByAccout(person.getAccout());
                }
                if( examinerService.findExaminerByAccout(temp, (Examination) excelUtil.getExamination().get(1))== null) {
                    examiner.setScore(0);
                    examiner.setStudentID(temp);
                    examiner.setExamination((Examination) excelUtil.getExamination().get(1));
                    examinerService.save(examiner);
                    ++count;
                }
            }
        } catch (RuntimeException e) {
            if(e.getMessage().contains("格式"))
                fileVO.setResultMessage("要读取的Excel的格式不正确，请查看标题！");
            else if(e.getMessage().contains("考试时间"))
                fileVO.setResultMessage("要读取的Excel的考试时间不正确，例子:yyyy-MM-dd HH:mm-HH:mm");
            else if(e.getMessage().contains("班级"))
                fileVO.setResultMessage("班级该时间已有考试！");
            logger.error(e);
            return ERROR;
        }
        fileVO.setResultMessage("成功导入考生信息" + count + "条记录，请查看数据库。");
        logger.trace("成功导入考生信息!");
        return SUCCESS;
    }

    public String recoverExcelByTest() {
        try {
            obj = excelUtil.readExcelByPath(fileVO.getFile(),
                    Test.class, 1, 0);
            if (fileVO.getSubject().equals("")) {
                fileVO.setResultMessage("请选择要导入试题的科目！");
                return ERROR;
            }
            Subject subject = subjectService.findSubjectBySubjectName(fileVO.getSubject());
            for (Object anObj : obj) {
                ts.add((Test) anObj);
            }
            String themeTemp;
            for (Test test : ts) {
                if("单选题".equals(test.getCategory().getType())||"多选题".equals(test.getCategory().getType())){
                    try {
                        themeTemp = Test.transformChoice(test.getTheme());
                    } catch (Exception e) {
                        logger.catching(e);
                        themeTemp = test.getTheme();
                    }
                }else {
                    themeTemp = test.getTheme();
                }
                if (testService.findTestByTheme(themeTemp) == null) {
                    if("单选题".equals(test.getCategory().getType())||"多选题".equals(test.getCategory().getType())){
                        try {
                            test.setTheme(Test.transformChoice(test.getTheme()));
                        } catch (Exception e) {
                            logger.catching(e);
                        }
                    }
                    test.setTestId(testService.getMaxTestId());
                    test.setId(0);
                    test.setDifficulty(0.0);
                    test.setSubject(subject);
                    test.setOwner(fileVO.getOwner());
                    test.setState(fileVO.getShare());
                    examinerService.save(test);
                    count++;
                }
            }
        } catch (RuntimeException e) {
            fileVO.setResultMessage("要读取的Excel的格式不正确，请查看标题！");
            logger.error(e);
            e.printStackTrace();
            return ERROR;
        }
        fileVO.setResultMessage("成功导入试题信息" + count + "条记录，请查看数据库。");
        logger.trace("成功导入试题信息!");
        return SUCCESS;
    }



    @Resource(name = "examinerServiceImpl")
    public void setExaminerService(ExaminerService examinerService) {
        this.examinerService = examinerService;
    }


    @Resource(name = "subjectServiceImpl")
    public void setSubjectService(SubjectService subjectService) {
        this.subjectService = subjectService;
    }

    @Resource(name = "personServiceImpl")
    public void setPersonService(PersonService personService) {
        this.personService = personService;
    }

    @Resource(name = "testServiceImpl")
    public void setTestService(TestService testService) {
        this.testService = testService;
    }

    @Override
    public FileVO getModel() {
        return fileVO;
    }

}
